from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from api.user_api import router as user_router
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.orm import Session
from datetime import datetime
import random
import os
from pathlib import Path
from commons.database import Database  # 添加Database类导入
from DAL.user import User
from DAL.category import Category
from DAL.product import Product
from DAL.order import Order, OrderItem
from DAL.seller_application import SellerApplication  # 确保导入所有模型

# 初始化FastAPI应用并配置Swagger文档元数据
app = FastAPI(
    title="项目API服务",
    description="使用FastAPI构建的RESTful API服务，支持自动生成Swagger文档",
    version="1.0.0",
    terms_of_service="http://example.com/terms/",
    contact={
        "name": "API支持",
        "url": "http://example.com/support",
        "email": "support@example.com",
    },
    license_info={
        "name": "MIT许可证",
        "url": "https://opensource.org/licenses/MIT",
    },
)

# 添加CORS中间件以允许跨域请求
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 允许所有来源，生产环境中应指定具体域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.mount("/web", StaticFiles(directory="web"), name="web")

# 注册API路由
app.include_router(user_router)

from api.category_api import router as category_router
app.include_router(category_router)

from api.product_api import router as product_router
app.include_router(product_router)

from api.order_api import router as order_router
app.include_router(order_router)

from api.seller_api import router as seller_router
app.include_router(seller_router)



# 初始化数据库
Database.init_db()
Database.create_tables()

# 导入用户模型并注册API
from DAL.user import User
from commons.api import APIBase
APIBase(app, User)



if __name__ == "__main__":
    import uvicorn
    # 启动服务，默认开启Swagger文档（访问http://localhost:8000/docs）
    uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)